using UnityEngine;
using TMPro;
using UnityEngine.UI;

public class AutoDestroy : MonoBehaviour
{
    public float maxLifeTime = 60f;  // 初始生存时间
    private float currentLifeTime;    // 当前生存时间
    private GameController gameController;
    public AudioSource audioSource;
    public AudioClip audioClip;
    private string username; // 存储用户名本地
    public Slider healthSlider; // 血条Slider

    void Start()
    {
        gameController = GameObject.FindObjectOfType<GameController>();
        audioSource = gameObject.AddComponent<AudioSource>();
        audioSource.clip = audioClip;
        audioSource.spatialBlend = 1.0f;
        audioSource.maxDistance = 20.0f;
        audioSource.minDistance = 1.0f;
        audioSource.rolloffMode = AudioRolloffMode.Linear;
        audioSource.loop = true;
        audioSource.Play();

        // 从对象的名称中提取用户名
        ExtractUsernameFromObjectName();

        // 设置TextMeshPro文本
        UpdateUsernameText(username);

        // 初始化生存时间
        currentLifeTime = maxLifeTime;

        // 在启动时调用生存时间更新方法
        UpdateLifeTime();

        // 调用InvokeRepeating方法，每隔一秒钟调用一次UpdateLifeTime方法
        InvokeRepeating("UpdateLifeTime", 1f, 1f);
    }

    // 从对象的名称中提取用户名
    private void ExtractUsernameFromObjectName()
    {
        int lastUnderscoreIndex = gameObject.name.LastIndexOf('_');

        if (lastUnderscoreIndex != -1)
        {
            username = gameObject.name.Substring(lastUnderscoreIndex + 1);
        }
        else
        {
            Debug.LogWarning("Object name format doesn't match expected format.");
        }
    }

    // 在合适的时机调用这个方法来更新TextMeshPro的文本
    private void UpdateUsernameText(string username)
    {
        // 从当前对象及其子对象中查找 TextMeshProUGUI 组件
        TextMeshProUGUI textMeshPro = GetComponentInChildren<TextMeshProUGUI>();

        if (textMeshPro != null)
        {
            textMeshPro.text = username;
            Debug.Log("Username set to: " + username);
        }
        else
        {
            Debug.LogError("TextMeshProUGUI not found on the same GameObject or its children!");
        }
    }

    // 更新生存时间的方法
    private void UpdateLifeTime()
    {
        // 检查是否有血条Slider引用
        if (healthSlider != null)
        {
            // 根据血条的值更新当前生存时间
            currentLifeTime = Mathf.Max(0, currentLifeTime - 1);  // 减少生存时间

            // 更新血条的值
            healthSlider.value = currentLifeTime / maxLifeTime;

            // 如果生存时间小于等于0，则销毁自身
            if (currentLifeTime <= 0)
            {
                DestroySelf();
            }
        }
    }

    private void DestroySelf()
    {
        //gameController.RemoveEnemyFromList(username);

        Destroy(audioSource);
        Destroy(gameObject);
    }
}
